<template>
  <Transition name="fade">
    <div v-if="modelValue" class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-30" style="z-index: 9999;">
      <div class="bg-white rounded-xl shadow-lg w-full max-w-4xl p-6 relative">
        <button class="absolute top-4 right-4 text-xl" @click="$emit('update:modelValue', false)">×</button>
        <h2 class="text-2xl font-bold text-blue-800 mb-6">路线规划</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <!-- 左侧输入面板 -->
          <div class="space-y-4">
            <div class="bg-gray-50 p-4 rounded-lg">
              <div class="space-y-3">
                <!-- 起点选择 -->
                <div>
                  <select
                    class="w-full px-4 py-2 border rounded-lg mb-2 bg-white"
                    @change="e => startPoint = e.target.value"
                    :value="startPoint"
                  >
                    <option value="">选择常用位置</option>
                    <option v-for="loc in COMMON_LOCATIONS" :key="loc" :value="loc">{{ loc }}</option>
                  </select>
                  <input
                    v-model="startPoint"
                    type="text"
                    placeholder="输入起点位置"
                    class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                  >
                </div>
                <!-- 终点选择 -->
                <div>
                  <select
                    class="w-full px-4 py-2 border rounded-lg mb-2 bg-white"
                    @change="e => endPoint = e.target.value"
                    :value="endPoint"
                  >
                    <option value="">选择常用位置</option>
                    <option v-for="loc in COMMON_LOCATIONS" :key="loc" :value="loc">{{ loc }}</option>
                  </select>
                  <input
                    v-model="endPoint"
                    type="text"
                    placeholder="输入终点位置"
                    class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"
                  >
                </div>
                <div class="flex space-x-2">
                  <button
                    v-for="mode in travelModes"
                    :key="mode.value"
                    @click="selectedMode = mode.value"
                    :class="[
                      'flex-1 px-4 py-2 rounded-lg',
                      selectedMode === mode.value 
                        ? 'bg-blue-600 text-white' 
                        : 'bg-gray-100 hover:bg-gray-200'
                    ]"
                  >
                    {{ mode.label }}
                  </button>
                </div>
                <button
                  @click="planRoute"
                  class="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-all"
                >
                  开始规划路线
                </button>
              </div>
            </div>
          </div>
          <!-- 右侧地图容器 -->
          <div class="md:col-span-2">
            <div id="trip-planner-map" class="h-[500px] rounded-lg overflow-hidden"></div>
            <div id="trip-route-panel" class="mt-4 bg-white p-4 rounded-lg shadow-md max-h-64 overflow-y-auto"></div>
          </div>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { MAP_CONFIG, initAMapLoader, TRAVEL_MODES } from '@/config/map'

const props = defineProps<{
  modelValue: boolean
  destination?: string
  position?: [number, number]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

// 常用位置
const COMMON_LOCATIONS = [
  '宝鸡火车站',
  '宝鸡南站',
  '法门寺',
  '太白山国家森林公园',
  '宝鸡市青铜器博物馆',
  '关山草原',
  '市政府',
  '陈仓老街',
  '人民公园'
]

const startPoint = ref('')
const endPoint = ref(props.destination || '')
const selectedMode = ref(TRAVEL_MODES.DRIVING.value)
const mapInstance = ref<any>(null)
const routePlanner = ref<any>(null)

const travelModes = [
  TRAVEL_MODES.DRIVING,
  TRAVEL_MODES.WALKING,
  TRAVEL_MODES.TRANSIT
]

const initMap = async () => {
  try {
    // 确保先加载地图脚本
    await initAMapLoader()
    
    // 确保地图容器存在
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 如果已存在地图实例，先销毁
    if (mapInstance.value) {
      mapInstance.value.destroy()
      mapInstance.value = null
    }
    
    // 创建新的地图实例
    mapInstance.value = new AMap.Map('trip-planner-map', {
      resizeEnable: true,
      center: props.position || MAP_CONFIG.DEFAULT_CENTER,
      zoom: MAP_CONFIG.DEFAULT_ZOOM,
      viewMode: '2D'
    })

    // 添加地图控件
    mapInstance.value.addControl(new AMap.Scale())
    mapInstance.value.addControl(new AMap.ToolBar())
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图加载失败，请刷新页面重试')
  }
}

const planRoute = async () => {
  if (!startPoint.value || !endPoint.value) {
    ElMessage.warning('请输入起点和终点')
    return
  }

  try {
    // 清理现有路线
    if (routePlanner.value) {
      routePlanner.value.clear()
      routePlanner.value = null
    }

    // 创建路线规划实例
    const options = {
      map: mapInstance.value,
      panel: 'trip-route-panel',
      city: '宝鸡市',
      autoFitView: true  // 自动调整视野
    }

    // 根据出行方式创建对应的路线规划实例
    const mode = Object.values(TRAVEL_MODES).find(mode => mode.value === selectedMode.value)
    
    switch (selectedMode.value) {
      case TRAVEL_MODES.DRIVING.value:
        routePlanner.value = new AMap.Driving({
          ...options,
          policy: mode?.policy ?? 0
        })
        break
      case TRAVEL_MODES.WALKING.value:
        routePlanner.value = new AMap.Walking(options)
        break
      case TRAVEL_MODES.TRANSIT.value:
        routePlanner.value = new AMap.Transfer({
          ...options,
          nightflag: true,
          policy: mode?.policy ?? 0
        })
        break
    }

    // 执行路线规划
    await new Promise((resolve, reject) => {
      routePlanner.value.search(
        [
          { keyword: startPoint.value },
          { keyword: endPoint.value }
        ],
        (status: string, result: any) => {
          if (status === 'complete') {
            resolve(result)
            ElMessage.success('路线规划成功')
          } else {
            reject(new Error(result?.info || '未知错误'))
          }
        }
      )
    })

  } catch (error: any) {
    console.error('路线规划失败:', error)
    ElMessage.error('路线规划失败: ' + error.message)
  }
}

// 监听目的地变化
watch(() => props.destination, (newVal) => {
  if (newVal) {
    endPoint.value = newVal
  }
})

// 监听弹窗显示状态
watch(() => props.modelValue, async (val) => {
  if (val) {
    if (props.destination) {
      endPoint.value = props.destination
    }
    // 确保清理之前的实例
    if (routePlanner.value) {
      routePlanner.value.clear()
      routePlanner.value = null
    }
    if (mapInstance.value) {
      mapInstance.value.destroy()
      mapInstance.value = null
    }
    // 初始化新的地图
    await initMap()
  } else {
    // 关闭弹窗时清理实例
    if (routePlanner.value) {
      routePlanner.value.clear()
      routePlanner.value = null
    }
    if (mapInstance.value) {
      mapInstance.value.destroy()
      mapInstance.value = null
    }
  }
}, { immediate: true })

onBeforeUnmount(() => {
  if (routePlanner.value) {
    routePlanner.value.clear()
    routePlanner.value = null
  }
  if (mapInstance.value) {
    mapInstance.value.destroy()
    mapInstance.value = null
  }
})
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

#trip-planner-map {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

#trip-route-panel {
  scrollbar-width: thin;
  scrollbar-color: #3b82f6 #f1f5f9;
}

#trip-route-panel::-webkit-scrollbar {
  width: 8px;
}

#trip-route-panel::-webkit-scrollbar-track {
  background: #f1f5f9;
}

#trip-route-panel::-webkit-scrollbar-thumb {
  background: #3b82f6;
  border-radius: 4px;
}
</style> 